import DebounceSelect from '@/components/DebounceSelect';
import type { ArticleRecord } from '@/DatabaseType/Article';
import { ArticleStatusTypeMap } from '@/DatabaseType/Article';
import {
  useTagFetchOptions,
  useUserFetchOptions,
} from '@/hooks/business/useFetchOptions';
import { deleteArticle, getArticleList } from '@/services/article';
import { IMAGE_FALL_BACK } from '@/constant';
import { ResponseCode } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Link } from '@umijs/max';

import { Button, Image, message, notification, Popconfirm, Tag } from 'antd';
import { useRef } from 'react';

const ArticleManagement = () => {
  const actionRef = useRef<ActionType>();

  // 获取用户列表
  const fetchUserList = useUserFetchOptions();
  const fetchTagList = useTagFetchOptions();

  const columns: ProColumns<ArticleRecord>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      width: 75,
      align: 'center',
    },
    {
      title: '标题',
      dataIndex: 'headline',
    },
    {
      title: '作者',
      dataIndex: 'author',
      render(dom, { user }) {
        return user?.nickname;
      },
      renderFormItem() {
        return (
          <DebounceSelect fetchOptions={fetchUserList} showArrow={false} />
        );
      },
      formItemProps: {
        name: 'userId',
      },
    },
    {
      title: '草稿',
      dataIndex: 'status',
      valueEnum: ArticleStatusTypeMap,
      render(dom, { status }) {
        const config = ArticleStatusTypeMap[status];
        return <Tag color={config.status}>{config.text}</Tag>;
      },
    },
    {
      title: '封面',
      dataIndex: 'coverUrl',
      render(text, { coverUrl }) {
        return (
          <Image
            style={{ objectFit: 'contain' }}
            width={60}
            height={60}
            src={coverUrl || IMAGE_FALL_BACK}
            alt="coverUrl"
            fallback={IMAGE_FALL_BACK}
          />
        );
      },
      hideInSearch: true,
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem() {
        return (
          <DebounceSelect
            mode="multiple"
            fetchOptions={fetchTagList}
            showArrow={false}
          />
        );
      },
    },
    {
      title: '摘要',
      dataIndex: 'outline',
    },
    {
      title: '存储文件',
      dataIndex: 'filename',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (text, { id }) => [
        <Link key="editor" to={`/markdown-editor?id=${id}`}>
          编辑
        </Link>,
        <Popconfirm
          key="delete-detail"
          title="确认删除该记录吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => sureDelete(id)}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 确认删除角色
  async function sureDelete(id: number) {
    try {
      const { code, message: msg } = await deleteArticle(id);
      if (code === ResponseCode.Success) {
        notification.success({ message: '删除成功' });
        actionRef.current?.reload();
      } else {
        notification.error({ message: msg || '删除失败' });
      }
    } catch (error: any) {
      notification.error({ message: error?.message || '删除角色失败' });
    }
  }

  // proTable 获取角色列表方法
  async function request(params: any) {
    try {
      const { code, data, message: msg } = await getArticleList(params);
      if (code === ResponseCode.Success) {
        return {
          data: data.list,
          total: data.total,
        };
      }
      throw new Error(msg);
    } catch (error: any) {
      message.error(error?.message);
      return {
        data: [],
        total: 0,
      };
    }
  }

  return (
    <PageContainer className="article-management">
      <ProTable<ArticleRecord>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          return request(params);
        }}
        scroll={{
          x: 1800,
        }}
        rowKey="id"
        search={{
          labelWidth: 100,
          defaultCollapsed: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Link
            to="/markdown-editor"
            style={{ color: 'white' }}
            key="add-detail"
          >
            <Button icon={<PlusOutlined />} type="primary">
              新增
            </Button>
          </Link>,
        ]}
      />
    </PageContainer>
  );
};

export default ArticleManagement;
